
package com.campus.common.net;
import java.io.*;
import java.net.Socket;

public class NetworkUtil {
    private Socket socket;
    private ObjectOutputStream out;
    private ObjectInputStream in;

    // 构造函数，传入一个已经建立的 socket
    public NetworkUtil(Socket socket) throws IOException {
        this.socket = socket;
        // 注意：必须先构造 ObjectOutputStream，再构造 ObjectInputStream
        this.out = new ObjectOutputStream(socket.getOutputStream());
        this.in = new ObjectInputStream(socket.getInputStream());
    }

    /**
     * 发送对象
     */
    public synchronized void send(Object obj) {
        try {
            out.writeObject(obj);
            out.flush();
        } catch (IOException e) {
            System.err.println("发送数据失败: " + e.getMessage());
        }
    }

    /**
     * 接收对象（阻塞）
     */
    public Object receive() {
        try {
            return in.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("接收数据失败: " + e.getMessage());
        }
        return null;
    }

    /**
     * 关闭资源
     */
    public void close() {
        try {
            if (in != null) in.close();
            if (out != null) out.close();
            if (socket != null) socket.close();
        } catch (IOException e) {
            System.err.println("关闭连接失败: " + e.getMessage());
        }
    }
}
